package com.ktwlrj.autotask.task;

import com.alibaba.fastjson.JSONObject;
import com.ktwlrj.autotask.config.MyTaskConfig;
import com.ktwlrj.autotask.config.TaskItem;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * 自动任务
 *
 * @author yuxf
 * @version 1.0
 * @date 2021/4/1 9:52
 */
@Component
@Slf4j
public class MyTask implements SchedulingConfigurer {

    @Autowired
    private MyTaskConfig taskConfig;


    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        for (TaskItem taskItem : taskConfig.getList()) {

           
            if (taskItem.getCrons() == null || taskItem.getCrons().size() == 0) {
                log.info("没有配置定时任务：" + taskItem.getName() + "的cron表达式");
                continue;
            }
            for (String cron : taskItem.getCrons()) {

                taskRegistrar.addCronTask(() -> {

                    requestTaskUrl(taskItem);
                }, cron);
            }
            log.info("注册定时任务：\n" + taskItem.getName() +"\n"+ taskItem.getUrl()+"\n"+ Arrays.toString(taskItem.getCrons().toArray(new String[0])) );
            if(taskItem.getImmediate())requestTaskUrl(taskItem);

        }
    }

    /**
     * 替换url的变量
     *
     * @param url
     * @return
     */
    private String getRealUrl(String url) {
        //处理url
        if (url == null || url.isEmpty()) {
            log.info("未配置url");
            return url;
        }
        if (url.contains("{date}")) {
            String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            url = url.replace("{date}", date);
        }
        return url;
    }


    private void requestTaskUrl(TaskItem taskItem) {
        try {
            String url=taskItem.getUrl();
            String realUrl = getRealUrl(url);
            log.info("请求：{},Url:{}", taskItem.getName(), realUrl);
            RestTemplate restTemplate = new RestTemplate();
            JSONObject jObject = restTemplate.getForObject(realUrl, JSONObject.class);
            log.info("响应："+jObject.toJSONString());
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }
}
